package com.graduation.cdm.funactivity.view;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.ActivityBean;
import com.graduation.cdm.funactivity.bean.DomainBean;
import com.graduation.cdm.funactivity.sqlitedraft.ActSqliteHelper;
import com.graduation.cdm.funactivity.util.DatePickActivity;
import com.graduation.cdm.funactivity.util.MultipartRequest;
import com.graduation.cdm.funactivity.view.mineview.ModifyPwdActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.OnClick;

import static com.graduation.cdm.funactivity.util.DateUtils.stringToDate;
import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;
import static com.graduation.cdm.funactivity.util.xUtilsImageUtils.display;

public class PublishActivity extends AppCompatActivity implements View.OnClickListener {

    int userId;

    ImageView ivBank;
    TextView btnSave;
    TextView btnPublish;
    Spinner spinnerLable;
    EditText edtActivityTitle;
    EditText repairBegtimeEt;
    EditText repairEndtimeEt;
    Spinner spinnerProvince;
    Spinner spinnerCity;
    EditText edtActivityAddress;
    ImageView ivFm;
    EditText edtDetail;
    EditText edtCare;
    EditText edtMaxpeople;

    private List<String> lableList = new ArrayList<>();
    private List<DomainBean.Domain> domainList = new ArrayList<>();
    private List<String> provinceList = new ArrayList<>();
    private List<String> cityList = new ArrayList<>();
    private List<Map<String,String>> provinceAllList = new ArrayList<>();
    private ArrayAdapter<String> adapter;

    public Boolean chooseImg = false;

    public static final int SELECT_PIC = 11;

    ActivityBean.Activity activity;

    private File file;
    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);

        getUser();
        ininView();

        fromCaogao();

        initSpinnerLable();
        provinceList.add("请选择省");
        initSpinnerAdapter("Province");
        getDomain("Province","0");
        initSpinnerAdapter("City");

        display(ivFm,preUrl+"lib/imgs/aa.png");

        createDb();

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //目录，文件名Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
            file = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());
            imageUri = Uri.fromFile(file);
        }

    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }

    private void getUser(){
        SharedPreferences sharedPreferences=getSharedPreferences("user_info",MODE_PRIVATE);
        userId = sharedPreferences.getInt("userId",1);
    }

    private void ininView(){
        ivBank = (ImageView) findViewById(R.id.iv_bank);
        ivFm = (ImageView) findViewById(R.id.iv_fm);
        btnSave = (TextView) findViewById(R.id.btn_save);
        btnPublish = (TextView) findViewById(R.id.btn_publish);
        edtActivityTitle = (EditText) findViewById(R.id.edt_activity_title);
        edtActivityAddress = (EditText) findViewById(R.id.edt_activity_address);
        edtDetail = (EditText) findViewById(R.id.edt_detail);
        edtCare = (EditText) findViewById(R.id.edt_care);
        repairBegtimeEt = (EditText) findViewById(R.id.repair_begtime_et);
        repairEndtimeEt = (EditText) findViewById(R.id.repair_endtime_et);
        edtMaxpeople = (EditText) findViewById(R.id.edt_maxpeople);
        spinnerLable = ((Spinner) findViewById(R.id.spinner_lable));
        spinnerProvince = ((Spinner) findViewById(R.id.spinner_province));
        spinnerCity = ((Spinner) findViewById(R.id.spinner_city));

        ivBank.setOnClickListener(this);
        ivFm.setOnClickListener(this);
        btnPublish.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        repairBegtimeEt.setOnClickListener(this);
        repairEndtimeEt.setOnClickListener(this);

        lableList.add("请选择标签");
        lableList.add("运动");
        lableList.add("技能");
        lableList.add("社交");
        lableList.add("美食");
        lableList.add("迷幻");
        lableList.add("远行");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 1) {
            // 选择预约时间的页面被关闭
            String date = data.getStringExtra("date");
            if (!repairBegtimeEt.getText().toString().equals(date)) {
                repairBegtimeEt.setText(data.getStringExtra("date"));
            } else {
                System.out.println("选择未变");
            }
        }
        if (resultCode == Activity.RESULT_OK && requestCode == 2) {
            // 选择预约时间的页面被关闭
            String date = data.getStringExtra("date");
            if (!repairEndtimeEt.getText().toString().equals(date)) {
                repairEndtimeEt.setText(data.getStringExtra("date"));
            } else {
                System.out.println("选择未变");
            }
        }
        switch (requestCode) {
            case 11:
                if (data != null) {
                    crop(data.getData());
                }
                break;
            case 12:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    System.out.println("extras"+extras);
                    if (extras != null) {
                        Bitmap bitmap = extras.getParcelable("data");
                        showImage(bitmap);
                    }
                }
                break;
        }
    }

    @OnClick({R.id.iv_bank, R.id.btn_save, R.id.btn_publish, R.id.repair_begtime_et, R.id.repair_endtime_et, R.id.iv_fm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_bank:
                finish();
                break;
            case R.id.btn_save:
                savedb();
                break;
            case R.id.btn_publish:
                getViewData();
                break;
            case R.id.repair_begtime_et:
                Intent intent1 = new Intent(getApplicationContext(), DatePickActivity.class);
                intent1.putExtra("date", repairBegtimeEt.getText().toString());
                startActivityForResult(intent1, 1);
                break;
            case R.id.repair_endtime_et:
                Intent intent2 = new Intent(getApplicationContext(), DatePickActivity.class);
                intent2.putExtra("date", repairEndtimeEt.getText().toString());
                startActivityForResult(intent2, 2);
                break;
            case R.id.iv_fm:
                //选择封面
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setType("image/*");
                /*intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image*//*");*/
                startActivityForResult(intent, SELECT_PIC);
                break;
        }
    }

    private void getDomain(final String namespace, final String parentId){
        String url=preUrl+"domain/getDomain";
        StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Gson gson = new Gson();
                DomainBean domainBean = gson.fromJson(s,DomainBean.class);
                if (namespace.equals("City")){
                    domainList.clear();
                }
                domainList.addAll(domainBean.domains);
                if (namespace.equals("Province")) {
                    for (int i = 0; i < domainList.size(); i++) {
                        Map<String,String> map = new HashMap<>();
                        map.put("id",domainList.get(i).id+"");
                        map.put("domainText",domainList.get(i).domainText);
                        provinceAllList.add(map);
                        provinceList.add(domainList.get(i).domainText);
                    }
                }else {
                    cityList.clear();
                    for (int i = 0; i < domainList.size(); i++) {
                        cityList.add(domainList.get(i).domainText);
                    }
                }
                initSpinnerAdapter(namespace);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("namespace",namespace);
                map.put("parentId",parentId);
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    private void initSpinnerAdapter(String namespace){
        if (namespace.equals("Province")) {
            adapter = new ArrayAdapter<String>(this,R.layout.spinner_item ,provinceList);
            adapter.setDropDownViewResource(R.layout.spinner_item);
            spinnerProvince.setAdapter(adapter);
            spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position!=0) {
                        String parentId = provinceAllList.get(position-1).get("id");
                        getDomain("City", parentId);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            if (activity!=null && provinceList.size()>1) {
                spinnerProvince.setSelection(Integer.parseInt(activity.activityProvince));
            }
        }else {
            cityList.add("请选择市");
            adapter = new ArrayAdapter<String>(this,R.layout.spinner_item ,cityList);
            adapter.setDropDownViewResource(R.layout.spinner_item);
            spinnerCity.setAdapter(adapter);
            spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            if (activity!=null && cityList.size()>1) {
                spinnerCity.setSelection(Integer.parseInt(activity.activityCity));
            }
        }
    }

    private void initSpinnerLable(){
        adapter = new ArrayAdapter<String>(this,R.layout.spinner_item ,lableList);
        adapter.setDropDownViewResource(R.layout.spinner_item);
        spinnerLable.setAdapter(adapter);
        if (activity!=null) {
            spinnerLable.setSelection(Integer.parseInt(activity.activityLabel));
        }
    }

    private void getViewData(){
        Boolean isOk = true;
        Long activityBeginTime = null;
        Long activityEndTime = null;
        String activityImgurl = null;
        String lable = spinnerLable.getSelectedItem().toString();
        String title = edtActivityTitle.getText().toString();

        //System.out.println("time="+repairBegtimeEt.getText().toString());
        if (repairBegtimeEt.getText().toString().equals("") || repairEndtimeEt.getText().toString().equals("")) {
            Toast.makeText(this, "活动开始和结束时间不能为空", Toast.LENGTH_SHORT).show();
            isOk = false;
            return;
        } else {
            activityBeginTime = stringToDate(repairBegtimeEt.getText().toString()+ ":00").getTime();
            activityEndTime = stringToDate(repairEndtimeEt.getText().toString()+":00").getTime();
            if (activityBeginTime > activityEndTime) {
                Toast.makeText(this, "活动开始时间必须小于结束时间", Toast.LENGTH_SHORT).show();
                isOk = false;
                return;
            }
        }

        String province = spinnerProvince.getSelectedItem().toString();
        String city = spinnerCity.getSelectedItem().toString();
        String activityAddress = edtActivityAddress.getText().toString();
        String activityDesc = edtDetail.getText().toString();
        String activityCare = edtCare.getText().toString();
        if (chooseImg) {
            activityImgurl = "lib/imgs/"+file.getName();
        } else {
            activityImgurl = "lib/imgs/aa.png";
        }

        Integer activityMaxPeopleNumber = Integer.parseInt((edtMaxpeople.getText().toString()).equals("") ? "0" : edtMaxpeople.getText().toString());
        Long creatTime = System.currentTimeMillis();

        ActivityBean activityBean = new ActivityBean();
        activity = activityBean.new Activity(lable,userId,title,activityBeginTime,activityImgurl,activityDesc,activityCare,activityEndTime,
                province+city+activityAddress,activityMaxPeopleNumber,1,System.currentTimeMillis(),0,province,city);

        if (isOk) {
            publish();
        }
    }

    private void publish(){
        uploadAvatarByMultipart();
        Toast.makeText(this, "正在发布...", Toast.LENGTH_SHORT).show();
        String url=preUrl+"activity/addActivity";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("success" + s);
                Toast.makeText(getApplicationContext(),"发布成功", Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("activityLabel",activity.activityLabel);
                map.put("activityTheme",activity.activityTheme);
                map.put("activityBegintime",activity.activityBegintime+"");
                map.put("activityEndtime",activity.activityEndtime+"");
                map.put("activityAddress",activity.activityAddress);
                map.put("activityImgurl",activity.activityImgurl);
                map.put("activityDesc",activity.activityDesc);
                map.put("activityCare",activity.activityCare);
                map.put("activityMaxPeopleNumber",activity.activityMaxPeopleNumber+"");
                map.put("isClassify",activity.isClassify+"");
                map.put("userId",activity.userId+"");
                map.put("stateId",activity.stateId+"");
                map.put("activityCreattime",activity.activityCreattime+"");
                map.put("activityProvince",activity.activityProvince);
                map.put("activityCity",activity.activityCity);
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

    public void savedb(){
        insertDb();
        //updateeDb();
        Toast.makeText(getApplicationContext(),"保存成功",Toast.LENGTH_SHORT).show();
    }

    //创建数据库的方法
    public void createDb() {
        //创建StuDBHelper对象
        ActSqliteHelper dbHelper = new ActSqliteHelper(this);
        //得到一个可读的SQLiteDatabase对象
        SQLiteDatabase db = dbHelper.getReadableDatabase();
    }

    //更新数据库的方法
    public void updateeDb() {
        // 数据库版本的更新,由原来的1变为2
        ActSqliteHelper dbHelper = new ActSqliteHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
    }

    public void insertDb() {
        ActSqliteHelper dbHelper = new ActSqliteHelper(this);
        //得到一个可写的数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        //生成ContentValues对象 //key:列名，value:想插入的值
        ContentValues cv = new ContentValues();

        Timestamp creatTime=new Timestamp(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String activity_creattime=sdf.format(creatTime);

        //往ContentValues对象存放数据，键-值对模式
        cv.put("activity_id", 1);
        cv.put("user_id", 4);
        cv.put("activity_label", spinnerLable.getSelectedItemPosition());
        cv.put("activity_theme", edtActivityTitle.getText().toString());
        cv.put("activity_begintime", repairBegtimeEt.getText().toString());
        cv.put("activity_creattime", System.currentTimeMillis());
        cv.put("activity_imgurl", "lib/imgs/aa.png");
        cv.put("activity_desc", edtDetail.getText().toString());
        cv.put("activity_care", edtCare.getText().toString());
        cv.put("activity_endtime", repairEndtimeEt.getText().toString());
        cv.put("activity_address", edtActivityAddress.getText().toString());
        cv.put("activity_max_people_number", Integer.parseInt((edtMaxpeople.getText().toString()).equals("") ? "0" : edtMaxpeople.getText().toString()));
        cv.put("activity_province", spinnerProvince.getSelectedItemPosition());
        cv.put("activity_city", spinnerCity.getSelectedItemPosition());
        //调用insert方法，将数据插入数据库
        long rowid=db.insert("act_table", null, cv);
        System.out.println("rowid="+rowid);
        //关闭数据库
        db.close();
    }

    public void fromCaogao() {
        Intent intent = this.getIntent();
        activity = (ActivityBean.Activity) intent.getSerializableExtra("activityInfo");
        System.out.println("initData+===" + activity);
        if (activity != null) {
            //spinnerLable
            //spinnerLable.setSelection(Integer.parseInt(activity.activityLabel));
            edtActivityTitle.setText(activity.activityTheme);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            repairBegtimeEt.setText(sdf.format(activity.activityBegintime));
            repairEndtimeEt.setText(sdf.format(activity.activityEndtime));
            edtActivityAddress.setText(activity.activityAddress);
            edtDetail.setText(activity.activityDesc);
            edtCare.setText(activity.activityCare);
            edtMaxpeople.setText(activity.activityMaxPeopleNumber + "");
            //spinnerProvince.setSelection(Integer.parseInt(activity.activityProvince));
            //spinnerCity.setSelection(Integer.parseInt(activity.activityCity));

            if (activity.activityImgurl != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(activity.activityImgurl);
                //ivFm.setImageBitmap(bitmap);
                //showImage(scaleBitmap(bitmap));
            }
        }
    }


    public void crop(Uri uri){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 12);
    }

    public void showImage(Bitmap bitmap) {
        ivFm.setImageBitmap(bitmap);//iv显示图片
        saveImage(bitmap);//保存文件
        System.out.println("file"+file);
        //uploadAvatarByMultipart();//上传服务器
        chooseImg = true;
    }

    public byte[] getImageBytes(Bitmap bmp){
        if(bmp==null){
            return null;
        }
        ByteArrayOutputStream baos =new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] imageBytes = baos.toByteArray();
        return imageBytes;
    }

    public void saveImage(Bitmap bitmap) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
    }


    private final String boundary ="apiclient-"+ System.currentTimeMillis();
    private final String mimeType ="multipart/form-data;boundary="+ boundary;
    private byte[] multipartBody;//保存内容的数组集合
    private Bitmap bitmap;//需要上传的图片
    private void uploadAvatarByMultipart(){
        String path = file.getAbsolutePath();
        bitmap = BitmapFactory.decodeFile(path);
        multipartBody =getImageBytes(bitmap);
        String url=preUrl+"user/uploadImage?userName="+file.getName();
        MultipartRequest multipartRequest = new MultipartRequest(url,ModifyPwdActivity.class,null,uploadAvatarByMultipartListener(),errorListener(),mimeType, multipartBody);
        MyApplication.getRequestQueue().add(multipartRequest);
    }

    private Response.Listener uploadAvatarByMultipartListener() {
        return new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Toast.makeText(getApplicationContext(),"成功！",Toast.LENGTH_SHORT).show();
                System.out.println(o.toString());
            }
        };
    }

    private Response.ErrorListener errorListener() {
        return new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"失败！",Toast.LENGTH_SHORT).show();
                System.out.println(volleyError.toString());
            }
        };
    }

}
